package com.jsnj33.pdaproject.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.device.ScanManager;
import android.device.scanner.configuration.PropertyID;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.jsnj33.pdaproject.R;
import com.jsnj33.pdaproject.adapter.ToollookAdapter;
import com.jsnj33.pdaproject.base.BaseActivity;
import com.jsnj33.pdaproject.bean.InspectionBean;
import com.jsnj33.pdaproject.bean.MainBean;
import com.jsnj33.pdaproject.bean.ToollookBean;
import com.jsnj33.pdaproject.constant.Constants;
import com.jsnj33.pdaproject.utils.LogUtils;
import com.jsnj33.pdaproject.utils.StringUtility;
import com.jsnj33.pdaproject.utils.ToastUtil;

import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ToollookActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "ToollookActivity";
    private final static String SCAN_ACTION = ScanManager.ACTION_DECODE;//default action

    private Vibrator mVibrator;
    private ScanManager mScanManager;
    private SoundPool soundpool = null;
    private int soundid;
    private boolean isScaning = false;
    private Button btnRetryScan;
    private TextView title;
    private TextView tv_gh_no;
    ToollookAdapter toollookAdapter;
    private List<MainBean> listAdress;
    private String tailUrl;

    private RecyclerView mRecyclerView;
    private BroadcastReceiver mScanReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            isScaning = false;
            soundpool.play(soundid, 1, 1, 0, 0, 1);
            mVibrator.vibrate(100);

            byte[] barcode = intent.getByteArrayExtra(ScanManager.DECODE_DATA_TAG);
            int barcodelen = intent.getIntExtra(ScanManager.BARCODE_LENGTH_TAG, 0);
            byte temp = intent.getByteExtra(ScanManager.BARCODE_TYPE_TAG, (byte) 0);
            Log.i(TAG, "onReceive: " + temp);
            String str = new String(barcode, 0, barcodelen);

            Log.i(TAG, "onReceive: " + str);
            if (StringUtility.isEmpty(str)) {
                ToastUtil.showGravityToast(ToollookActivity.this, "扫码失败！", Gravity.CENTER, 0, 0);
                return;
            }
//            String sbs = str.substring(0, 2);
            /**
             * 如果扫到的码为4位数,则是工号
             * 否则就是设备号/制令单
             */
            if (str.length() == 4) {
//                tv_gh_no.setText(str);
                ToastUtil.showLongToast(ToollookActivity.this, "制令单号异常");
            } else {
                try {
                    tv_gh_no.setText(str);
                    setGoodsData(str);
                } catch (Exception e) {
                    LogUtils.e(TAG, e.getMessage() + "");
                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.activity_tool_look);
        btnRetryScan = findViewById(R.id.btnRetryScan);

        mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
        initData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        initScan();
        IntentFilter filter = new IntentFilter();
        int[] idbuf = new int[]{PropertyID.WEDGE_INTENT_ACTION_NAME, PropertyID.WEDGE_INTENT_DATA_STRING_TAG};
        String[] value_buf = mScanManager.getParameterString(idbuf);
        if (value_buf != null && value_buf[0] != null && !value_buf[0].equals("")) {
            filter.addAction(value_buf[0]);
        } else {
            filter.addAction(SCAN_ACTION);
        }
        registerReceiver(mScanReceiver, filter);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mScanManager != null) {
            mScanManager.stopDecode();
            isScaning = false;
        }
        unregisterReceiver(mScanReceiver);
    }

    private void initScan() {
        mScanManager = new ScanManager();
        mScanManager.openScanner();

        mScanManager.switchOutputMode(0);
        soundpool = new SoundPool(1, AudioManager.STREAM_NOTIFICATION, 100); // MODE_RINGTONE
        soundid = soundpool.load("/etc/Scan_new.ogg", 1);
    }

    private void initData() {
        title = findViewById(R.id.title);
        tv_gh_no = findViewById(R.id.tv_gh_no);
        mRecyclerView = (RecyclerView) findViewById(R.id.mRecyclerView);
        GridLayoutManager linearLayoutManager = new GridLayoutManager(this, 1);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        linearLayoutManager.supportsPredictiveItemAnimations();
        mRecyclerView.setLayoutManager(linearLayoutManager);
        Intent intent = getIntent();
        if (intent != null) {
            title.setText(getIntent().getStringExtra("title"));
            listAdress = (List<MainBean>) getIntent().getSerializableExtra("list");
            tailUrl = listAdress.get(0).getAddress();
        }
        toollookAdapter = new ToollookAdapter(this, null);
        mRecyclerView.setAdapter(toollookAdapter);
        btnRetryScan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toollookAdapter.clear();
                tv_gh_no.setText("");
            }
        });
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
        }
    }

    /**
     * 扫描制令单号
     *
     * @param osNo
     */
    private void setGoodsData(final String osNo) {
        String url = Constants.BASEURL + Constants.workProByPda + "?mo_no=" + osNo;
        Log.i(TAG, "setGoodsData: " + url);
        RequestParams requestParams = new RequestParams(url);
        requestParams.setConnectTimeout(300000);
        requestParams.setReadTimeout(300000);
        x.http().get(requestParams, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Log.d(TAG, "onSuccess: " + result.toString());
                try {
                    ToollookBean toollookBean = new Gson().fromJson(result, ToollookBean.class);
                    if (toollookBean.getRespCode() == 1) {
                        List<ToollookBean.DataBean> list = toollookBean.getData();
                        toollookAdapter.updata(list);
                    }
                } catch (Exception e) {
                    Log.i(TAG, "Exception: " + e.getMessage());

                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.d(TAG, "Throwable: " + ex.getMessage());

            }

            @Override
            public void onCancelled(CancelledException cex) {
                Log.d(TAG, "onCancelled: ");
            }

            @Override
            public void onFinished() {
                Log.d(TAG, "onFinished: ");
            }
        });
    }
}

